package SocketClient;

import UI.MyVideoCanvas;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ClientVideo {
    private int port;
    private String host;
    private MyVideoCanvas canvas=null;
    public ClientVideo(int port,String host,MyVideoCanvas canvas){
        this.host=host;
        this.port=port;
        this.canvas=canvas;
    }

    Socket clientVideo=null;
    public void init() throws IOException {
        clientVideo=new Socket(host,port+1);
        if(clientVideo==null){
            System.out.println("未能连接服务器!");
            return ;
        }
        InputStream is = clientVideo.getInputStream();
        byte values[]=new byte[640*480*3];
        int realReadSize=0;
        int readSize=0;
        while(true){
            realReadSize=0;
            readSize=0;
            while(realReadSize!=640*480*3){
                readSize= is.read(values,realReadSize,640*480*3-realReadSize);
                if(readSize>=0){
                    realReadSize+=readSize;
                }else{
                    break;
                }
            }
            if(realReadSize==640*480*3){

                Mat frame=new Mat(480,640, CvType.CV_8UC3);
                frame.put(0,0,values);
                if (!frame.empty()){
                    canvas.frame=frame;
                    canvas.repaint();
                }else{
                    continue;
                }
            }
        }
    }
}
